package com.s59.players.conntroller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.s59.players.entity.Clubs;
import com.s59.players.entity.Players;
import com.s59.players.service.ClubsService;
import com.s59.players.service.PlayService;
import com.s59.players.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/plays")
public class PlayConntroller {
    @Autowired
    private PlayService playService;
    @Autowired
    private ClubsService clubsService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping
    public String getAll(String pname, Long cid, Model model){
        model.addAttribute("playList", playService.getAll(pname, cid));
        model.addAttribute("pname", pname);
        model.addAttribute("cid", cid);
        return "play/index";
    }

    @GetMapping("/clubs")
    @ResponseBody
    public String clubs() throws JsonProcessingException {
        String clubsString = redisUtil.get("clubs");
        if (clubsString==null){
            List<Clubs> list = clubsService.xlkList();
            clubsString = new ObjectMapper().writeValueAsString(list);
            redisUtil.set("clubs",clubsString);
            return clubsString;
        }else{
            return clubsString;
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(Long pid){
        return playService.delete(pid)+"";
    }

    @GetMapping("/add")
    public String add(){
        return "play/add";
    }

    @PostMapping("/insert")
    public String insert(Players players, HttpServletResponse response) throws IOException {
        int i = playService.insert(players);
        if (i == 1){
            response.getWriter().print("<script>alert('新增成功');location.href='/plays'</script>");
        }else{
            response.getWriter().print("<script>alert('新增失败');location.href='/plays/add'</script>");
        }
        return null;
    }

    @GetMapping("/getUp/{pid}")
    public String getUp(@PathVariable Long pid, Model model){
        model.addAttribute("play",playService.get(pid));
        return "play/update";
    }

    @PostMapping("/update")
    public String update(Players players, HttpServletResponse response) throws IOException {
        int i = playService.update(players);
        if (i == 1){
            response.getWriter().print("<script>alert('修改成功');location.href='/plays'</script>");
        }else {
            response.getWriter().print("<script>alert('修改失败');location.href='/plays/update'</script>");
        }
        return null;
    }

}
